// 您可以在进行窗口交互
// utools文档

// https://www.u.tools/docs/developer/api.html#%E7%AA%97%E5%8F%A3%E4%BA%A4%E4%BA%92
window.versions={
    node: () => process.versions.node,
    chrome: () => process.versions.chrome,
    electron: () => process.versions.electron
}

import { clipboard, nativeImage } from 'electron'
import { encrypt as aesEncrypt, decrypt as aesDecrypt } from 'crypto-js/aes'
import UTF8 from 'crypto-js/enc-utf8'

// 定义剪贴板数据类型
interface CustomClipboardItem {
  id: string
  type: 'text' | 'image' | 'file'
  content: string | Buffer
  timestamp: number
  deviceId: string
  encrypted?: boolean
}

// 剪贴板操作 API
window.clipboardAPI = {
  // 获取剪贴板内容
  getClipboard: (): CustomClipboardItem | null => {
    const text = clipboard.readText()
    const image = clipboard.readImage()
    const files = clipboard.readBuffer('FileNameW')
    
    const id = Date.now().toString()
    const timestamp = Date.now()
    
    if (text) {
      return {
        id,
        type: 'text' as const,
        content: text,
        timestamp,
        deviceId: ''
      } as CustomClipboardItem
    }
    
    if (!image.isEmpty()) {
      return {
        id,
        type: 'image' as const,
        content: image.toDataURL(),
        timestamp,
        deviceId: ''
      } as CustomClipboardItem
    }
    
    if (files) {
      return {
        id,
        type: 'file' as const,
        content: files,
        timestamp,
        deviceId: ''
      } as CustomClipboardItem
    }
    
    return null
  },

  // 写入剪贴板
  setClipboard: (item: CustomClipboardItem) => {
    switch (item.type) {
      case 'text':
        clipboard.writeText(item.content as string)
        break
      case 'image':
        const image = nativeImage.createFromDataURL(item.content as string)
        clipboard.writeImage(image)
        break
      case 'file':
        clipboard.writeBuffer('FileNameW', item.content as Buffer)
        break
    }
  },

  // 加密内容
  encrypt: async (content: string, key: string) => {
    return aesEncrypt(content, key).toString()
  },

  // 解密内容
  decrypt: async (content: string, key: string) => {
    const bytes = aesDecrypt(content, key)
    return bytes.toString(UTF8)
  }
}

// 插件入口
window.exports = {
  'clipboard': {
    mode: 'none',
    args: {
      enter: () => {
        window.utools.showMainWindow()
      }
    }
  }
}
